

// pages/rent/rent.js
Page({

  data: {
    orderid:"",
    itemid:'',
    // 地址信息
    name:'',
    phone:'',
    address:'',
    // 个人信息
    ava:'',
    nickname:'',
    //商品信息
    pic:'',
    title:'',
    deposit:'',
    value:'',
    //租用时间
    starttime:'请选择开始时间',
    finishtime:'请选择结束时间',
    startdate:'',
    day:0,
    //显示物品发货框
    charge:'none',
    //租用方式
    way:'请选择>',
    sendway:[],
    //订单生成时间
    ordertime:'',
    // 订单备注
    remark:'',
    //总计
    sum:0

  },

  onLoad(options){

    //获取订单时间
    var date = new Date().toJSON().substring(0, 10);
    var ordertime = new Date().toJSON().substring(0, 10) + ' ' + new Date().toTimeString().substring(0,8);
    this.setData({
      startdate:date,
      ordertime:ordertime,
    })

    var that = this;
    var itemid = options.itemid;
    this.setData({
      itemid:itemid,
      orderid:options.orderid
    })

    //从订单信息进入则查找
    if(options.orderid){
      wx.request({
        url: 'http://127.0.0.1:8080/order/orderById',
        method:"POST",
        data:{orderid:options.orderid},
        success(res){
          // console.log(res)
          var ordeinfo = res.data[0];
          that.setData({
            name:ordeinfo.receiveName,
            phone:ordeinfo.receivePhone,
            address:ordeinfo.deliveryAddress,
            starttime:ordeinfo.rentStartTime,
            finishtime:ordeinfo.rentEndTime,
            day:ordeinfo.rentDays,
            remark:ordeinfo.orderRemark,
            way:ordeinfo.deliveryMethod,
            sum:ordeinfo.rentPayment,
          })
        }
      })
    }

    //购买商品时渲染
    if(!options.orderid){
      // 渲染初始选择的地址
      wx.request({
        url: 'http://127.0.0.1:8080/address/selectAddress',
        method:"POST",
        data:{
          openid:wx.getStorageSync('openid')
        },
        success(res){
          if(res.data.length != 0){
            var addressinfo = res.data[0];
            // console.log(addressinfo)
            that.setData({
              name:addressinfo.rentName,
              phone:addressinfo.rentPhone,
              address:addressinfo.rentAddress
            })
          }
          
        }
      })
    }

    // 渲染物品信息
    wx.request({
      url: 'http://127.0.0.1:8080/item/selectItemByItemId',
      method:"POST",
      data:{
        itemid:itemid
      },
      success(res){
        var iteminfo = res.data[0];
        var rentway = []
        for(var i=0;i<iteminfo.rentWay;i++){
          // '送货上门','物品自提','当面交易'
          if(iteminfo.rentWay[i] == 0){rentway.unshift("送货上门");}
          if(iteminfo.rentWay[i] == 1){rentway.unshift("物品自提");}
          if(iteminfo.rentWay[i] == 2){rentway.unshift("当面交易");}
        }

        that.setData({
          ava:iteminfo.wxAva,
          nickname:iteminfo.nickName,
          pic:JSON.parse(iteminfo.itemPic)[0],
          title:iteminfo.itemTitle,
          deposit:iteminfo.deposit,
          value:iteminfo.dayRent,
          sendway:rentway
        })
        // console.log(res.data[0])
      }
    })
    // console.log(options)

  },
  onShow(){  
    
    let pages = getCurrentPages();
    let currPage = pages[pages.length - 1];
    // console.log(currPage);
    //此处既是上一页面传递过来的值
    
  },
  
  // 选择地址
  chooseaddress(){
    wx.navigateTo({
      url: '/pages/address/address?fromwhere=1',
    })
  },
  // 选择开始时间
  startdate(e){
    // console.log(e)
    var starttime = e.detail.value
    if(this.data.finishtime != '请选择结束时间'){
      var day =  this.checkDate(starttime,this.data.finishtime)
      if(day <= 0)
      {
        // console.log('fail')
        wx.showToast({
          title: '非法信息选择',
          icon:'error',
          duration:2000,
          success: (res) => {},
        })
      }else{
        var deposit = this.data.deposit
        var value = this.data.value
        this.setData({
          starttime:e.detail.value,
          day:day,
          sum:(deposit+value*day)
          })
      }
    } else{
      console.log(1)
       this.setData({
        starttime:e.detail.value,
        sum:0,
        day:0
      })
    }

    
  },
  // 选择结束时间
  finishdate(e){
    // console.log(e)
    var finishtime = e.detail.value
   
    if(this.data.starttime != '请选择开始时间'){
      var day = this.checkDate(this.data.starttime,finishtime)
      // console.log(day)
        if(parseInt(day) <= 0){
          wx.showToast({
            title: '非法信息选择',
            icon:'error',
            duration:2000,
            success: (res) => {},
          })
        }else{
          var deposit = this.data.deposit
          var value = this.data.value
          this.setData({
            finishtime:e.detail.value,
            day:day,
            sum:(deposit+value*day)
          })
        }
    }else{
       this.setData({
      finishtime:e.detail.value,
      sum:0
      })
    }
    
  },
  // 判断时间大小以及获取天数
  checkDate(startTime,endTime) {

    var start_date = new Date(startTime.replace(/-/g, "/"));
    var end_date = new Date(endTime.replace(/-/g, "/"));
    //转成毫秒数，两个日期相减
    var ms = end_date.getTime() - start_date.getTime();
    //转换成天数
    var day = parseInt(ms / (1000 * 60 * 60 * 24));
    //do something
    // console.log("day = ", day);
    return day;

  },
  // 选择送货方式
  openway(){
    this.setData({
      charge:'true'
    })
  },
  chooseway(e){
    console.log(e)
    var index = e.currentTarget.dataset.index;
    this.setData({
      way:this.data.sendway[index],
      charge:'none'
    })
  },
  // 获得订单备注
  getremark(e){
    this.setData({
      remark:e.detail.value
    })
  },

  // 支付
  buy(){
    var day = this.data.day;
    var way = this.data.way;
    var that = this;

    wx.request({
      url: 'http://127.0.0.1:8080/user/personInfo',
      method:"POST",
      data:{openid:wx.getStorageSync('openid')},
      success(res){
        // console.log(res)
        if(day == 0){
          wx.showToast({
            title: '日期未选',
            icon:'error',
            duration:2000,
            success: (res) => {},
          })
        }else if(way == '请选择>'){
          wx.showToast({
            title: '送货方式未选',
            icon:'error',
            duration:2000,
            success: (res) => {},
          })
        }else{
          wx.showModal({
            content: '您的余额:'+res.data[0].money,
            title: '确定支付该订单吗?',
            success: (result) => {
              // 确认付款则直接生成待发货订单
              if(result.confirm){
                if(res.data[0].money < that.data.sum ){
                  wx.showToast({
                    title: '余额不足',
                    icon:"error"
                  })
                }else{
                  wx.request({
                    url: 'http://127.0.0.1:8080/user/updateMoney',
                    method:"POST",
                    data:{
                      openid:wx.getStorageSync('openid'),
                      money:parseFloat(res.data[0].money - that.data.sum)
                    },
                    success(res){
                      if(res.data){
                        wx.showToast({
                          title: '支付成功',
                          icon:"error"
                        })
                      }
                    }
                  })
                 //没有订单号生成订单 两种情况付款
                  if(!that.data.orderid){
                    // 生成当前时间
                    var orderdata = that.data
                    var newDateTime=new Date().getTime();
                    var orderid = "o"+newDateTime;
                      console.log("o"+newDateTime);
                    // 生成付款时间
                    var orderpaytime = new Date().toJSON().substring(0, 10) + ' ' + new Date().toTimeString().substring(0,8);
                    // 订单信息
                    var data = {
                      orderid:orderid,
                      ordergentime:orderdata.ordertime,
                      orderpaytime:orderpaytime,
                      //交货时间
                      rentstarttime:orderdata.starttime,
                      rentendtime:orderdata.finishtime,
                      //续租时间
                      rentdays:orderdata.day,
                      rentpayment:orderdata.sum,
                      deliverymethod:orderdata.way,
                      receivename:orderdata.name,
                      receivephone:orderdata.phone, 
                      deliveryaddress:orderdata.address,
                      //订单状态 应该为待收货
                      //交易快照
                      orderremark:orderdata.remark,
                      userid:wx.getStorageSync('openid'),
                      itemid:orderdata.itemid
                    }
                    wx.request({
                      url: 'http://127.0.0.1:8080/order/payOrder',
                      method:"POST",
                      data:data,
                      success(res){
                        // console.log(res);
                        if(res.data){
                          console.log('44444')
                          console.log(orderdata.itemid)
                          // 物品被租用修改为租赁中
                          wx.request({
                            url: 'http://127.0.0.1:8080/item/rentstate',
                            method:"POST",
                            data:{itemid:orderdata.itemid},
                            success(res){
                              console.log(res)
                            }
                          })
                          console.log('11111')
                          wx.switchTab({
                            url: '/pages/mine/mine',
                          })
                        }
                      }
                    })
                  }else{
                      //有订单号更新订单
                      var orderdata = that.data
                      // 付款时间
                      var orderpaytime = new Date().toJSON().substring(0, 10) + ' ' + new Date().toTimeString().substring(0,8);
                    var data = {
                      orderid:orderdata.orderid,
                      orderpaytime:orderpaytime,
                      //交货时间
                      rentstarttime:orderdata.starttime,
                      rentendtime:orderdata.finishtime,
                      //续租时间
                      rentdays:orderdata.day,
                      rentpayment:orderdata.sum,
                      deliverymethod:orderdata.way,
                      receivename:orderdata.name,
                      receivephone:orderdata.phone, 
                      deliveryaddress:orderdata.address,
                      //订单状态 应该为待收货
                      orderstate:"待发货",
                      //交易快照
                      orderremark:orderdata.remark,
                    }
                    wx.request({
                      url: 'http://127.0.0.1:8080/order/updateToWaitItem',
                      method:"POST",
                      data:data,
                      success(res){
                        // console.log(res)
                        if(res.data){
                          // 物品被租用修改为租赁中
                          wx.request({
                            url: 'http://127.0.0.1:8080/item/rentstate',
                            method:"POST",
                            data:{itemid:orderdata.itemid},
                            success(res){
                              console.log(res)
                            }
                          })
                          wx.switchTab({
                            url: '/pages/mine/mine',
                          })
                        }
                      }
                    })
                  }
                }
              }else{
                // 没有订单且不付款生成未付款订单
                if(!that.data.orderid){
                    // 未确定则生成待付款订单
                    // 生成当前时间
                    var orderdata = that.data
                    var newDateTime=new Date().getTime();
                    var orderid = "o"+newDateTime;
                      console.log("o"+newDateTime);
                    // 生成付款时间
                    var orderpaytime = new Date().toJSON().substring(0, 10) + ' ' + new Date().toTimeString().substring(0,8);
    
                    // 订单信息
                    var data = {
                      orderid:orderid,
                      ordergentime:orderdata.ordertime,
                      // orderpaytime:orderpaytime,
                      //交货时间
                      rentstarttime:orderdata.starttime,
                      rentendtime:orderdata.finishtime,
                      //续租时间
                      rentdays:orderdata.day,
                      rentpayment:orderdata.sum,
                      deliverymethod:orderdata.way,
                      receivename:orderdata.name,
                      receivephone:orderdata.phone, 
                      deliveryaddress:orderdata.address,
                      //订单状态 应该为待收货
                      //交易快照
                      orderremark:orderdata.remark,
                      userid:wx.getStorageSync('openid'),
                      itemid:orderdata.itemid
                    }
                    wx.request({
                      url: 'http://127.0.0.1:8080/order/noPayOrder',
                      method:"POST",
                      data:data,
                      success(res){
                        // console.log(res);
                        if(res.data){
                          wx.switchTab({
                            url: '/pages/mine/mine',
                          })
                        }
                      }
                    })
    
                }else{
                      //有订单号更新订单
                      var orderdata = that.data
                      // 付款时间
                      // var orderpaytime = new Date().toJSON().substring(0, 10) + ' ' + new Date().toTimeString().substring(0,8);
                              
                      var data = {
                        orderid:orderdata.orderid,
                        orderpaytime:null,
                        //交货时间
                        rentstarttime:orderdata.starttime,
                        rentendtime:orderdata.finishtime,
                        //续租时间
                        rentdays:orderdata.day,
                        rentpayment:orderdata.sum,  
                        deliverymethod:orderdata.way,
                        receivename:orderdata.name,
                        receivephone:orderdata.phone, 
                        deliveryaddress:orderdata.address,
                        orderstate:"待付款",
                        //订单状态 应该为待收货
                        //交易快照
                        orderremark:orderdata.remark,
                      }
                        wx.request({
                          url: 'http://127.0.0.1:8080/order/updateToWaitItem',
                          method:"POST",
                          data:data,
                          success(res){
                            // console.log(res)
                            if(res.data){
                            }
                         }
                      })
                }
              }
            },
          })
        } 
      }
    })

 
  }

})